package configs

import (
	"os"

	"gopkg.in/yaml.v3"
)

const configPath = "../configs/config.yaml"

type Config struct {
	Server struct {
		Host    string `yaml:"host"`
		Port    string `yaml:"port"`
		Timeout struct {
			Server int `yaml:"server"`
			Read   int `yaml:"read"`
			Write  int `yaml:"write"`
			Idle   int `yaml:"idle"`
		} `yaml:"timeout"`
		DB struct {
			Host string `yaml:"host"`
			Port string `yaml:"port"`
			User string `yaml:"user"`
			Pass string `yaml:"pass"`
			Name string `yaml:"name"`
			SSL  string `yaml:"ssl"`
		} `yaml:"db"`
	} `yaml:"server"`
}

type SecretKey struct {
	Key string `yaml:"secretkey"`
}

func InitConfig() (*Config, error) {
	cfg := &Config{}

	file, err := os.Open(configPath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	d := yaml.NewDecoder(file)

	if err := d.Decode(&cfg); err != nil {
		return nil, err
	}

	return cfg, nil
}

func JWTSecretKey() *SecretKey {
	sk := &SecretKey{}

	file, err := os.Open(configPath)
	if err != nil {
		return nil
	}
	defer file.Close()

	d := yaml.NewDecoder(file)

	if err := d.Decode(&sk); err != nil {
		return nil
	}

	return sk
}
